package cn.lx.stack;


import java.util.Iterator;

/**
 * Created by Administrator on 2017/3/21 0021.
 */
public class MyArrayStack<Item>  implements Stack<Item>,Iterable<Item>{
    Item[] items = null;//集合的底层数组实现
    int N = 0;//当前集合容量

    public MyArrayStack(int num){
        items = (Item[]) new Object[num];//java不支持泛型数组，可以使用强转的方式实现
    }

    public Item pop() {
        if(N == 0){
            return  null;
        }
        Item item = items[--N];
        items[N] = null;//防止出现对象游离，因为数组还保存着对元素的引用，java不会回收该对象
        if(N == items.length/4){
            resize(items.length/2);
        }

        return item;
    }

    public void push(Item item) {
        if(N == items.length){
            resize(2*items.length);
        }
        items[N++] = item;
    }

    public boolean isEmpty() {
        return N==0;
    }

    @Override
    public int size() {
        return N;
    }

    //实现自动扩容的方式
    private void resize(int num){
        Item[] temp = (Item[]) new Object[num];
        for(int i = 0;i<N ; i++){
            temp[i] = items[i];
        }
        items = temp;
    }

    public Iterator<Item> iterator() {
        return new MyArrayStackIterator();
    }

    private class  MyArrayStackIterator implements Iterator<Item>{
        private int i = N;
        public boolean hasNext() {
            return i>0;
        }

        public Item next() {
            return items[--i];
        }

    }

    public static void main(String[] args) {
        MyArrayStack<String> stacks = new MyArrayStack<>(10);
        stacks.push("1");
        stacks.push("2");
        for(String s : stacks){
            System.out.println(s);
        }
    }
}
